package com.ccpdown.util.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.webkit.URLUtil;
import android.widget.Toast;

public class FileDownUtil {

	public String currentTempFilePath;
	public File tmpFile;
	public Context context;

	public FileDownUtil(Context context) {
		this.context = context;
	}

	public void getFile(final String strPath) {
		if (CheckNetwork()) {
			try {
				Runnable r = new Runnable() {
					private Handler handler = new Handler() {
						private ProgressDialog pgd;

						@Override
						public void handleMessage(Message msg) {
							// TODO Auto-generated method stub
							switch (msg.what) {
							case 1:
								pgd = ProgressDialog.show(context,
										"DownLoading",
										"Loading. Please wait...", true);
								break;
							default:
								if (pgd != null) {
									pgd.cancel();
								}
								break;
							}
							super.handleMessage(msg);
						}
					};

					@Override
					public void run() {
						try {
							loading();
							getDataSource(strPath);
							loaded();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							Toast.makeText(context, "下载过程出错",
									Toast.LENGTH_SHORT);
						}

					}

					private void loading() {
						handler.sendEmptyMessage(1);
					}

					private void loaded() {
						handler.sendEmptyMessage(0);
					}
				};
				new Thread(r).start();

			} catch (RuntimeException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// check the network if working
	public boolean CheckNetwork() {
		boolean flag = false;
		ConnectivityManager cwjManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cwjManager.getActiveNetworkInfo() != null)
			flag = cwjManager.getActiveNetworkInfo().isAvailable();
		if (!flag) {
			String str = "请开启GPRS或WIFI网络连接";
			Builder b = new AlertDialog.Builder(context).setTitle("没有可用的网络")
					.setMessage(str);
			b.setNegativeButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Intent mIntent = new Intent("/");
					ComponentName comp = new ComponentName(
							"com.android.settings",
							"com.android.settings.WirelessSettings");
					mIntent.setComponent(comp);
					mIntent.setAction("android.intent.action.VIEW");
					context.startActivity(mIntent);
				}
			}).setNeutralButton("取消", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					dialog.cancel();
				}
			}).create();
			b.show();
		}

		return flag;
	}

	// downloading the file
	public void getDataSource(String strPath) throws Exception {
		if (!URLUtil.isNetworkUrl(strPath)) {
			throw new RuntimeException("网络连接出现问题");
		}
		URL myURL = new URL(strPath);
		URLConnection conn = myURL.openConnection();
		conn.connect();
		InputStream is = conn.getInputStream();
		if (is != null) {
			tmpFile = File.createTempFile(getFileNa(strPath), "."
					+ getFileEx(strPath));
			currentTempFilePath = tmpFile.getAbsolutePath();
			FileOutputStream fos = new FileOutputStream(tmpFile);
			byte[] buf = new byte[128];
			int numread = 1;
			while (true) {
				numread = is.read(buf);
				if (numread <= 0) {
					break;
				}
				fos.write(buf, 0, numread);
			}
			openFile(tmpFile);
			fos.close();
		} else {
			throw new RuntimeException("文件传输产生错误");
		}
		is.close();
	}

	// 打开文件；
	public void openFile(File file) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);

		String type = getType(file);
		intent.setDataAndType(Uri.fromFile(file), type);
		context.startActivity(intent);
	}

	// 取得文件的类型名；
	public String getType(File file) {
		String type = "";
		String fName = file.getName();
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();
		if (end.equals("apk")) {
			type = "application/vnd.android.package-archive";
		}
		return type;
	}

	// 后缀
	public String getFileEx(String uri) {
		return uri.substring(uri.lastIndexOf(".") + 1, uri.length())
				.toLowerCase();
	}

	// 不加后缀的文件名；
	public String getFileNa(String uri) {
		return uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("."));
	}

	// 从文件全路径名中获取带后缀的文件名
	public String getFileNameWithExt(String path) {
		if (path.length() > 1) {
			int pos = path.lastIndexOf("/");
			if (pos < path.length() - 1) {
				return path.substring(pos + 1);
			}
		}
		return null;
	}
}
